import React, {forwardRef, useMemo, useRef} from 'react';
import {GModalButton} from '../ModalButton';
import {GForm} from '../Form';
import {GModalFormProps} from './ModalFormProps';

export const GModalForm = forwardRef((props: GModalFormProps, ref: any) => {
  const formRef = useRef<any>();

  const form = useMemo(() => {
    return <GForm {...props.form} ref={formRef}/>;
  }, [props.form]);

  const button = useMemo(() => {
    return (
      <GModalButton
        {...props.button}
        onOk={() => {
          return formRef.current.submit()
            .then(() => {
              return props.button?.onOk?.();
            })
        }}
      >
        {form}
      </GModalButton>
    );
  }, [props.button, props.form]);

  return <>{button}</>;
});
